<?php
namespace app\index\controller;
use app\common\mq\Rabbitmq;
use think\facade\Log;

class Mq
{
    private static $channel_name = 'joker'; //路由键
    /**
     * 生产者
     */
    public function produce()
    {
        $rabbitmq = new Rabbitmq();
        $res = $rabbitmq->connect();
        if($res){
            echo 'connect success!' . "\n";
            $msg = ['key' => 'name', 'value' => 'weihaoyu'];
            $msg = json_encode($msg);
            $rabbitmq->publish($msg, '', self::$channel_name);
            echo 'send success：' . $msg . "\n";
        }else{
            echo 'connect error!' . "\n";
        }
    }

    /**
     * 消费者
     */
    public function consume()
    {
        $callBack = function ($message){
            //print_r($message);
            $body = $message->body;
            if(!empty($body)){
                echo "\n" . 'consume success：' . $body . "\n";
                $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
            }
        };
        try{
            $rabbitmq = new Rabbitmq();
            $res = $rabbitmq->connect();
            $receiver = new self();
            $rabbitmq->consumer(self::$channel_name, '', [$receiver, 'callback']);
        }catch(\Exception $e){
            dump($e->getMessage());
        }
    }

    public function callback($message)
    {
        //print_r($message);
        $body = $message->body;
        Log::write($body);
        if(!empty($body)){
            echo "\n" . 'consume success：' . $body . "\n";
            $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
        }
    }
}
